
from google.appengine.api import mail

from email_template.imp import service_imp

def Notify(key, data, to=None, cc=None, override=False):
  """

  Args:
    key: str, The `key` of the EmailTemplate to utilize for generating email
      deliveries.
    data: dict, A dict object whose values will be utilized to populate
      `subject` and `body` templates from the EmailTemplate designated by the
      `key` argument.
    to: set<email_address>, Optional argument. By default the to argumenet
      will be merged with the `to` field from the EmailTemplate. If the
      "override" argument is set to True, then the value of this argument
      will replace the `to` value from the EmailTemplate. Note: if "override"
      is set to True, then the "to" argument must be supplied with at least
      one(1) email address entry in the list.
    cc: set<email_address>, Optional argument. By default the "cc" argument
      will be merged with the `cc` field from EmailTemplate. If the
      "overriddent" argument is set to true, then the value of the argument
      will replace the `cc` value from EmailTemplate. Note: if "overridden"
      is set to True,this argument is still optional.
    override: boolean,  Optional, that default to False. This argument
      affects the behavior of the the behavior of the `to` and `cc` fields.
      If False, then the "to and "cc" arguments will be merged with the `to`
      and `cc` fields fo the EmailTemplate. If True, then the EmailTemplate
      `to` and `cc` fields are ignored, and only the "to" and "cc" arguments
      are used to construct the email delivery.
  Exceptions:
    ValueError:
      - Invalid email address in the set of "to" argument.
      - Invalid email address in the set of "cc" argument.
      - "override" set to True, and the "to" recipient set does not contain
        at least one valid email address.
  """
  #TODO(raulg): Add validation
  to = set() if to is None else to
  cc = set() if cc is None else to
  if not to and override:
    raise ValueError('"override" set to True, and the "to" recipient set does '
                     'not contain at least one valid email address')

  for address in to:
    if not mail.is_email_valid(address):
      raise ValueError('Invalid email address in to list: %s', address)

  for address in cc:
    if not mail.is_email_valid(address):
      raise ValueError('Invalid email address in cc list: %s', address)

  #TODO(raulg): This call needs to be asynchronous.
  service_imp.Notify(key, data, to, cc, override)
